﻿@page "/longrunningtask"

<h1>Closing Modal after long-running task</h1>

<hr class="mb-5" />

<p>
    A long-running task can be executed and a modal can be closed programatically after it.
</p>

<div class="card mb-4">
    <div class="card-body">
        <p class="card-text">
            <code>
                @("var loading = Modal.Show<Loading>();")<br />
                @("await Task.Delay(5000);")<br />
                <br />
                @("loading.Close();")<br />
            </code>
        </p>
    </div>
</div>

<p>Result: @_result;</p>

<button @onclick="ShowModal" class="btn btn-primary">Long-running task default ModalResult</button>
<button @onclick="ShowOkResultModal" class="btn btn-primary">Long-running task OK result</button>
<button @onclick="ShowCancelModal" class="btn btn-primary">Long-running task with cancelled result</button>


@code {

    [CascadingParameter] public IModalService Modal { get; set; } = default!;

    string? _result;

    async Task ShowModal()
    {
        var options = new ModalOptions
        {
            HideCloseButton = false,
            DisableBackgroundCancel = true,
            HideHeader = true
        };
        var loading = Modal.Show<Loading>(string.Empty, options);

        await Task.Delay(5000);

        loading.Close();
        var result = await loading.Result;
        if (result.DataType == typeof(object))
            _result = "Modal returned with default ModalResult";

        StateHasChanged();
    }

    async Task ShowOkResultModal()
    {
        var options = new ModalOptions
        {
            HideCloseButton = false,
            DisableBackgroundCancel = true,
            HideHeader = true
        };
        var loading = Modal.Show<Loading>(string.Empty, options);

        await Task.Delay(5000);

        loading.Close(ModalResult.Ok("Closed with OK result"));
        var result = await loading.Result;
        if (result.Data is not null && result.DataType == typeof(string))
            _result = result.Data.ToString()!;

        StateHasChanged();
    }

    async Task ShowCancelModal()
    {
        var options = new ModalOptions
        {
            HideCloseButton = false,
            DisableBackgroundCancel = true,
            HideHeader = true
        };
        var loading = Modal.Show<Loading>(string.Empty, options);

        await Task.Delay(5000);

        loading.Close(ModalResult.Cancel());
        var result = await loading.Result;
        if (result.Cancelled)
            _result = "Closed with Cancelled result";

        StateHasChanged();
    }

}